#!/bin/bash
set -exuo pipefail

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
DAEMON_APP_ID=$1

# Define the paths to the source and target version files
DAEMON_SOURCE_VERSION="$DIR/version"
DAEMON_TARGET_VERSION="/Library/PrivilegedHelperTools/$DAEMON_APP_ID.app/Contents/Library/version"

# Function to read and compare file contents
compare_contents() {
    local source_content
    local target_content

    source_content=$(<"$1")
    target_content=$(<"$2")

    if [ "$source_content" = "$target_content" ]; then
        return 0  # Contents are the same
    else
        return 1  # Contents are different
    fi
}

# Function to check if an update is required
is_update_required() {
    local source_file="$1"
    local target_file="$2"

    # Check if the target file exists
    if [ ! -e "$target_file" ]; then
        return 0  # Target file does not exist, an update is required
    fi

    # Compare contents if the target file exists
    if compare_contents "$source_file" "$target_file"; then
        return 1  # Update is not required
    else
        return 0  # Update is required
    fi
}

# Check if an update is required
if is_update_required "$DAEMON_SOURCE_VERSION" "$DAEMON_TARGET_VERSION"; then
    DAEMON_SOURCE_PLIST_PATH="$DIR/launchd.plist"
    DAEMON_TARGET_PLIST_PATH="/Library/LaunchDaemons/$DAEMON_APP_ID.plist"

    DAEMON_SOURCE_APP_PATH="$DIR/../../../$DAEMON_APP_ID.app"
    DAEMON_TARGET_APP_PATH="/Library/PrivilegedHelperTools/$DAEMON_APP_ID.app"

    # Check if DAEMON_TARGET_PLIST_PATH already exists and unload it if needed
    if [ -e "$DAEMON_TARGET_PLIST_PATH" ]; then
        launchctl unload "$DAEMON_TARGET_PLIST_PATH"
    fi

    # Delete DAEMON_TARGET_APP_PATH if it exists
    if [ -e "$DAEMON_TARGET_APP_PATH" ]; then
        rm -rf "$DAEMON_TARGET_APP_PATH"
    fi

    cp "$DAEMON_SOURCE_PLIST_PATH" "$DAEMON_TARGET_PLIST_PATH"
    chown root:wheel "$DAEMON_TARGET_PLIST_PATH"
    cp -R "$DAEMON_SOURCE_APP_PATH" "$DAEMON_TARGET_APP_PATH"
    launchctl load "$DAEMON_TARGET_PLIST_PATH"

fi
